package core

import (
	"think/route"
	"net/http"
)

// App 应用程序核心结构
type App struct {
	router     *route.Router
	middleware []func(http.Handler) http.Handler
}

// NewApp 创建一个新的应用实例
func NewApp() *App {
	return &App{
		router:     route.NewRouter(),
		middleware: make([]func(http.Handler) http.Handler, 0),
	}
}

// Use 添加中间件
func (app *App) Use(m func(http.Handler) http.Handler) {
	app.middleware = append(app.middleware, m)
}

// Router 获取路由器实例
func (app *App) Router() *route.Router {
	return app.router
}

// Run 启动HTTP服务器
func (app *App) Run(addr string) error {
	// 构建中间件链
	handler := http.Handler(app.router)
	for i := len(app.middleware) - 1; i >= 0; i-- {
		handler = app.middleware[i](handler)
	}

	return http.ListenAndServe(addr, handler)
}